import time

import requests
from loguru import logger

from apps.pdd.pdd.utils.app.so.demo_rpc import gen_anti_content as gen_anti_content_app
from apps.pdd.pdd.utils.js import gen_anti_content, MSG_MAP


class Crawler(object):
    session = requests.Session()
    app_version = "7.6.0"
    channel = "oppo"
    phone_version = "R8"
    device_id = "eDX37CJK"
    session.headers = {
        "Host": "api.pinduoduo.com",
        "etag": device_id,
        "referer": "Android",
        "p-appname": "pinduoduo",
        "x-pdd-info": "bold_free%3Dfalse%26bold_product%3D%26front%3D0%26tz%3DAsia%2FShanghai",
        "x-pdd-queries": f"width=1080&height=1920&net=1&brand={channel}&model={phone_version}&osv=9&appv={app_version}&pl=2",
        "p-proc": "main",
        "p-mediainfo": "player=2.0.4&rtc=1.0.0",
        "user-agent": f"android Mozilla/5.0 (Linux; Android 9; {channel} {phone_version} Build/PQ3A.190605.04081832; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/91.0.4472.114 Mobile Safari/537.36  phh_android_version/{app_version} phh_android_build/a29b63f6c97be3675aff8f5f661fcddf1f6b713b phh_android_channel/{channel} pversion/0",
        # "pdd-config": "V4:001.067300",
        # "multi-set": "1,0,100000107",
    }

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        pass

    def gen_anti_content(self, time, device_id=None):
        rt = gen_anti_content_app(time=time, device_id=device_id)
        print(rt)
        return rt

    def __init__(self, cookie):
        logger.debug(self.session.headers)
        if "PDDAccessToken" not in cookie:
            raise Exception("cookie 缺少 PDDAccessToken")
        self.session.cookies.update(cookie)

    def query_cat_goods(self, mall_id, page_no=1):
        session_cookie = self.session.cookies.get_dict()
        pdd_user_id = session_cookie.get("pdd_user_id")
        anti_token = self.gen_anti_content(time=int(time.time() * 1000))
        anti_content_dict = gen_anti_content(
            {
                "serverTime": int(time.time() * 1000),
            },
            {
                "touchEventData": True,
                "clickEventData": True,
                "focusblurEventData": True,
                "changeEventData": True,
                "locationInfo": True,
                "referrer": True,
                "browserSize": True,
                "browserInfo": True,
                "token": True,
                "fingerprint": True,
            },
        )
        h5_anti_content = anti_content_dict["anti_content"]
        headers = {
            **self.session.headers,
            "content-type": "application/json;charset=UTF-8",
            "anti-token": anti_token,
            "accesstoken": session_cookie.get("PDDAccessToken"),
        }

        url = "https://api.pinduoduo.com/api/turing/mall/query_cat_goods"
        params = {
            "pdduid": pdd_user_id,
            "anticontent": h5_anti_content,
            "anti_content": h5_anti_content,
            "category_id": "0",
            "type": "0",
            "mall_id": mall_id,
            "page_size": "20",
            "sort_type": "_sales",
            "refer_page_param": "undefined",
            "refer_page_sn": "0",
            "msn": "",
            "x_query": "",
            "flip": "",
            "list_id": "",
            "page_from": "39",
            "query": "",
            "goods_id": "0",
            "new_store_goods": "",
            "show_priority_type": "1",
            "show_condition": "null",
            "data_type_list": "1",
            "pair_goods_id_list": "",
            "filter_condition": "",
            "query_shipping_option": "1",
            "card_num_after_last_card": "[]",
            "card_num_total": "",
            "page_no": page_no,
        }
        print(params)
        print(headers)
        response = self.session.get(url, headers=headers, params=params)
        print(response)
        print(response.text)

    def query_mall_category_list(self, mall_id):
        session_cookie = self.session.cookies.get_dict()
        pdd_user_id = session_cookie.get("pdd_user_id")
        anti_token = self.gen_anti_content(time=int(time.time() * 1000), device_id=self.device_id)
        url = "https://api.pinduoduo.com/api/turing/mall/query_mall_category_list"
        headers = {
            **self.session.headers,
            "content-type": "application/json;charset=UTF-8",
            "anti-token": anti_token,
            "accesstoken": session_cookie.get("PDDAccessToken"),
            "referer": "https://m.pinduoduo.net/mall_page.html?mall_id=982418036",
        }

        params = {"pdduid": pdd_user_id, "mall_id": mall_id, "msn": "dgzc3dqthhxr6ngctc3eerqwxm_axbuy"}
        response = self.session.get(url, headers=headers, params=params)
        print(response)
        print(response.text)

        resp = response.json()
        if "error_code" in resp:
            logger.error(MSG_MAP.get(resp["error_code"]))

    def get_mall_certificates(self):
        import requests

        headers = {
            "Host": "m.pinduoduo.net",
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "user-agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 15_8_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Model/iPhone8,1 phh_ios_version/7.7.0 phh_ios_build/202404211256 pversion/0",
            "x-pdd-queries": "width=750.000000&height=1334.000000&brand=apple&model=iPhone 6s&osv=15.8.2&appv=7.7.0&pl=iOS&net=1",
            "p-uno-context": '{"ls":0,"webp":0}',
        }
        cookies = {
            "webp": "1",
            "pdd_vds": "gaALjOWEJGSOknMNKaSIkbqykGKoJyqIzIJmVyqIXIjOSQFbHISLSGHoVmKt",
            "group_rec_list": "group_rec_list_t3jrva",
            "ETag": "Q6bgvlp5",
            "PDDAccessToken": "LX7TLTRC2ZW76MUAOWNDHNZKD2YHYJAMPLUTFULKOIHSDVFGYWOA1205c0c",
            "install_token": "622F9637-7271-4B65-BD54-FBF6BD2FD362",
            "pdd_user_id": "8664931343452",
            "pdd_user_uin": "YWUE7W3HDBQDMFVN7JEQRRXSMA_GEXDA",
            "_nano_fp": "Xpman0P8XpPbXqTxno_jIK~Xu9cgO54dLNjPGw2k",
            "api_uid": "Ck1lFWYttB6s/QBb37rDAg==",
        }
        url = "https://m.pinduoduo.net/mall_certificates.html"
        params = {
            "refer_page_id": "10039_1714293827244_2523247540",
            "refer_page_name": "mall_subject",
            "mall_id": "255735058",
            "refer_page_sn": "10039",
            "_x_query": "发现美假发",
        }
        response = requests.get(url, headers=headers, cookies=cookies, params=params)

        print(response.text)
        print(response)


if __name__ == "__main__":
    ck = {
        # 'api_uid': 'CiFp9mYuAIcAoABeA0ZsAg==',
        # 'acid': '1a0d8f78dba208afc41c44b1b66159b5',
        # 'PDDAccessToken': '2TS6S4CCXEWEPUFOOLV5YOXK2DI4CAA7WOYAQ4W56LOYTL7O2STQ1205479',
        # 'pdd_user_id': '2466085755988',
        # 'pdd_user_uin': 'GXJTZOUCPDYV55PPKYN3OZTUGA_GEXDA',
        # 'mobile_id': '7256676885099520000738',
        # 'mobile_des': '167****0738',
        # 'api_uid': 'CihcoGYuB4YXtgBrA3uKAg==',
        # 'acid': 'adde39d9b1261a562529431bdd58fc70',
        # 'PDDAccessToken': 'EZOMAQ2ODBTOPF5PPHXA2SD76XHUOTLX2ACW7HRPTU5IWK3PVAUQ122073d',
        # 'pdd_user_id': '7752204003847',
        # 'pdd_user_uin': 'XQMWPXLHAPVJZ6LODCS6RV4LYY_GEXDA',
        # 'mobile_id': '3937377188218306560614', 'mobile_des': '156****3614',
        # 'api_uid': 'Ck9gbWYuCETDTwBnA0lZAg==',
        # 'acid': 'c4ce819bed114a98e0a660820a4d08ca',
        # 'PDDAccessToken': 'F4IJ3YULFMUH5UMCINHCOVNMZNNCHSXPTJPOYUZ5LNAVEAMLL2WQ122d503',
        # 'pdd_user_id': '6932690837205',
        # 'pdd_user_uin': 'AQGTM2TSVSSOQCK5SPP63VLRQU_GEXDA',
        # 'mobile_id': '7025190009631211520477',
        # 'mobile_des': '167****2477',
        "api_uid": "CiVws2YvlUJtxwBtClO9Ag==",
        "acid": "dc486f8b59419a2059b5c8e358659477",
        "PDDAccessToken": "FMHWBAIGVN73FSJOS56WEKLEG5U5IK6DXB3IIPFAA6VR6KFF2Z5A121ed23",
        "pdd_user_uin": "QGHVOCINWX4HY5OVUVR5C64XEQ_GEXDA",
        "mobile_id": "4716698570907484160223",
        "mobile_des": "155****5223",
        "pdd_user_id": "9715481226733",
    }
    with Crawler(ck) as self:
        # self.query_cat_goods(514487514)
        self.query_mall_category_list(982418036)
